package com.xiaxueqi.service.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.niagara.security.auth.UserDetailService;
import com.niagara.security.auth.entity.Permission;
import com.niagara.security.auth.entity.UserDetail;
import com.niagara.service.base.BaseService;
import com.xiaxueqi.entity.security.AppPermission;
import com.xiaxueqi.entity.security.AppRolePermission;
import com.xiaxueqi.entity.security.AppUser;
import com.xiaxueqi.entity.security.AppUserRole;

public class UserDetailServiceImpl implements UserDetailService {

	@Autowired
	private BaseService baseService;

	public UserDetail loadUserDetailByLoginId(String loginId) {
		Long userId;
		String password;
		AppUser appUser = new AppUser();
		appUser.setLoginId(loginId);
		appUser = this.baseService.get(AppUser.class, appUser,
				"select_by_condition");
		// 用户名不存在
		if (appUser == null)
			return null;
		else {
			userId = appUser.getId().longValue();
			password = appUser.getPassword();
			AppUserRole appUserRole = new AppUserRole();

			// 根据用户ID获得此用户的用户角色
			appUserRole.setUserId(appUser.getId());
			List<AppUserRole> roleList = this.baseService.find(
					AppUserRole.class, appUserRole,
					"select_by_condition");

			// 根据用户可能的多种角色来取得各种角色的权限
			AppRolePermission rolePermission = new AppRolePermission();
			List<AppRolePermission> rolePermissionList = new ArrayList<AppRolePermission>();
			for (int i = 0; i < roleList.size(); i++) {
				rolePermission.setRoleId(roleList.get(i).getRoleId());
				List<AppRolePermission> list = this.baseService.find(
					AppRolePermission.class, rolePermission,
					"select_by_condition");
				rolePermissionList.addAll(list);
			}

			// 根据用户的权限ID来取得权限的具体权限值
			List<Permission> permissionList = new ArrayList<Permission>();
			for (int i = 0; i < rolePermissionList.size(); i++) {
				AppPermission appPermission = new AppPermission();
				appPermission = this.baseService.get(AppPermission.class,
						rolePermissionList.get(i).getPermissionId());

				// 将AppPermission类中的值设置到Permission中
				Permission p = new Permission();
				translate(appPermission, p);
				permissionList.add(p);

			}

			// 将所取到的权限转换成数组形式
			Permission[] permissions = new Permission[permissionList.size()];
			permissions = permissionList.toArray(permissions);

			UserDetail detail = new UserDetail(userId, loginId, password,
					permissions);

			return detail;
		}
	}

	// 将AppPermission类中的值设置到Permission中
	private void translate(AppPermission src, Permission des) {
		des.setId(src.getId());
		des.setName(src.getName());
		des.setPermissionKey(src.getPermissionKey());
		des.setPermissionType(src.getPermissionType());
	}

}
